package com.jmb.api.common.exception;

import com.jmb.api.common.result.Result;
import com.jmb.api.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result error(Exception e){
        log.info("全局异常处理，打印的异常错误:",e);
        return Result.fail();
    }
    @ResponseBody
    @ExceptionHandler(LeaseException.class)
    public Result error(LeaseException e){
        log.info("异常错误:",e);
        return Result.fail(e.getCode(),e.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        String errorMsg = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return Result.fail(ResultCodeEnum.WEB_API_PARAM_VALID_ERROR.getCode(), errorMsg);
    }
}
